package com.rocksdata.mc.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ctz.commonframe.ui.TitleBarActivity;
import com.ctz.commonframe.utils.DateUtil;
import com.rocksdata.mc.entity.PayrollInfo;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.entity.PayrollDetail;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by 陈堂正 on 2017/2/24.
 */
@ContentView(R.layout.activity_payroll)
public class PayrollActivity extends TitleBarActivity {
    @ViewInject(R.id.tv_payroll_total)
    private TextView tvTotal;
    @ViewInject(R.id.tv_payroll_date)
    private TextView tvDate;
    @ViewInject(R.id.iv_previous)
    private ImageView ivPrevious;
    @ViewInject(R.id.iv_next)
    private ImageView ivNext;
    @ViewInject(R.id.elv_payroll)
    private ExpandableListView elvPayroll;

    private String yearMonth;
    private PayrollInfo info;
    private PayDetailListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleMiddleText("工资单");

        Date date = new Date(System.currentTimeMillis());
        yearMonth = getYearMonth(date);
        refreshDate();
        getPayrollData();
    }

    @Event(value = {R.id.iv_previous, R.id.iv_next})
    private void onClick(View view){
        switch (view.getId()) {
            case R.id.iv_previous:
                addMonth(-1);
                refreshDate();
                getPayrollData();
                break;
            case R.id.iv_next:
                addMonth(1);
                refreshDate();
                getPayrollData();
                break;
        }
    }

    private void addMonth(int count){
        Calendar c = Calendar.getInstance();
        c.setTime(DateUtil.string2Date(yearMonth, DateUtil.DATE_FORMAT_YYYYMM));
        c.add(Calendar.MONTH, count);
        yearMonth = getYearMonth(c.getTime());
    }

    private String getYearMonth(Date date){
        return DateUtil.date2String(date, DateUtil.DATE_FORMAT_YYYYMM);
    }

    private void getPayrollData(){
        showLoadingDialog();
        ivNext.setEnabled(false);
        ivPrevious.setEnabled(false);
        BusinessManager.getPayrollManager().getPayrollInfo(yearMonth, PayrollInfo.class, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if(isSuccess){
                    info = (PayrollInfo) object;
                }else{
                    info = null;
                }
                updateUI();
                dismissLoadingDialog();
            }
        });
    }

    private void updateUI(){
        refreshPreviousAndNext();
        if(info == null){
            tvTotal.setText("无当月数据");
        }else {
            tvTotal.setText(getFormatValue(info.getTotal().getItemValue()) + "元");
        }
        refreshDetailList();
    }

    private void refreshDate(){
        tvDate.setText(yearMonth.substring(0, 4) + "年" + yearMonth.substring(4, 6) + "月收入");
    }

    private void refreshPreviousAndNext(){
        Date currentDate = new Date(System.currentTimeMillis());
        if(getYearMonth(currentDate).equals(yearMonth)){
            ivNext.setVisibility(View.GONE);
        }else{
            ivNext.setVisibility(View.VISIBLE);
            ivNext.setEnabled(true);
        }
        Integer ym = Integer.parseInt(yearMonth);
        Integer currentYm = Integer.parseInt(getYearMonth(currentDate));
        //只允许查3年内的数据
        if(currentYm - ym == 300){
            ivPrevious.setVisibility(View.GONE);
        }else{
            ivPrevious.setVisibility(View.VISIBLE);
            ivPrevious.setEnabled(true);
        }
    }

    private void refreshDetailList(){
        adapter = new PayDetailListAdapter(PayrollActivity.this, info);
        elvPayroll.setAdapter(adapter);
    }

    private String getFormatValue(float value){
        DecimalFormat decimalFormat = new DecimalFormat(".00");
        return decimalFormat.format(value);
    }

    private class PayDetailListAdapter extends BaseExpandableListAdapter{
        private Context context;
        private PayrollInfo payrollInfo;

        public PayDetailListAdapter(Context context, PayrollInfo payrollInfo){
            this.context = context;
            this.payrollInfo = payrollInfo;
        }

        @Override
        public int getGroupCount() {
            return payrollInfo == null ? 0 : 2;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            if(payrollInfo != null){
                if(groupPosition == 0){
                    return payrollInfo.getIncomeSalary().getIncomeDetail().size();
                }else if(groupPosition == 1){
                    return payrollInfo.getExpendSalary().getExpendDetail().size();
                }
            }
            return 0;
        }

        @Override
        public PayrollDetail getGroup(int groupPosition) {
            if(groupPosition == 0){
                return payrollInfo.getIncomeSalary().getIncomeTotal();
            }else if(groupPosition == 1){
                return payrollInfo.getExpendSalary().getExpendTotal();
            }
            return null;
        }

        @Override
        public PayrollDetail getChild(int groupPosition, int childPosition) {
            if(groupPosition == 0){
                return payrollInfo.getIncomeSalary().getIncomeDetail().get(childPosition);
            }else if(groupPosition == 1){
                return payrollInfo.getExpendSalary().getExpendDetail().get(childPosition);
            }
            return null;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupViewHolder holder;
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_payroll_list_group, null);
                holder = new GroupViewHolder();
                holder.tvLabel = (TextView) convertView.findViewById(R.id.tv_payroll_parent_label);
                holder.tvMoney = (TextView) convertView.findViewById(R.id.tv_payroll_parent_money);
                holder.ivLabel = (ImageView) convertView.findViewById(R.id.iv_payroll_parent_label);
                holder.ivFlag = (ImageView) convertView.findViewById(R.id.iv_payroll_parent_expand_flag);
                convertView.setTag(holder);
            }else{
                holder = (GroupViewHolder) convertView.getTag();
            }
            final PayrollDetail detail = getGroup(groupPosition);
            holder.tvLabel.setText(detail.getItemName());
            holder.tvMoney.setText(getFormatValue(detail.getItemValue()));
            holder.ivFlag.setImageResource(isExpanded ? R.mipmap.ic_indicator_expanded : R.mipmap.ic_indicator_unexpanded);

            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder holder;
            if(convertView == null){
                holder = new ChildViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.item_payroll_list_child, null);
                holder.tvLabel = (TextView) convertView.findViewById(R.id.tv_payroll_child_label);
                holder.tvMoney = (TextView) convertView.findViewById(R.id.tv_payroll_child_money);
                convertView.setTag(holder);
            }else{
                holder = (ChildViewHolder) convertView.getTag();
            }
            PayrollDetail obj = getChild(groupPosition, childPosition);
            holder.tvLabel.setText(obj.getItemName());
            holder.tvMoney.setText(getFormatValue(obj.getItemValue()));

            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        class GroupViewHolder{
            TextView tvLabel;
            TextView tvMoney;
            ImageView ivLabel;
            ImageView ivFlag;
        }

        class ChildViewHolder{
            TextView tvLabel;
            TextView tvMoney;
        }
    }
}
